package com.leyou.item.web;

import com.leyou.common.vo.PageResult;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/brand")
public class BrandController {

    @Autowired
    private BrandService brandService;

    /**
     * 分页条件查询品牌列表
     * @param key       搜索关键字
     * @param page      当前页
     * @param rows      页大小
     * @param sortBy    排序的字段
     * @param desc      是否降序
     * @return          返回的我们定义的分页结果对象：PageResult
     */
    @GetMapping("/page")
    public ResponseEntity<PageResult<BrandDTO>> queryBrandPage(
            @RequestParam(value="key",required = false) String key,
            @RequestParam(value="page",defaultValue = "1") Integer page,
            @RequestParam(value="rows",defaultValue = "5") Integer rows,
            @RequestParam(value="sortBy",defaultValue = "id") String sortBy,
            @RequestParam(value="desc",defaultValue = "false") Boolean desc
    ){
        PageResult<BrandDTO> result =brandService.queryBrandPage(key, page, rows, sortBy, desc);
        return ResponseEntity.ok(result);
    }

    /**
     * 保存品牌信息：并且维护分类和品牌的中间表
     * @param brand     品牌的dto
     * @param cids      分类的id集合
     * @return          无
     */
    @PostMapping
    public ResponseEntity<Void> saveBrand(BrandDTO brand, @RequestParam("cids")List<Long> cids){
        brandService.saveBrand(brand, cids);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据分类id查询品牌列表
     * @param cid   分类id
     * @return      品牌的DTO集合
     */
    @GetMapping("/of/category")
    public ResponseEntity<List<BrandDTO>> queryBrandListByCategoryId(@RequestParam("id") Long cid){
        List<BrandDTO> brandDTOList = brandService.queryBrandListByCategoryId(cid);
        return ResponseEntity.ok(brandDTOList);
    }


    /**
     * 通过品牌的id查询品牌详情
     * @param id    品牌的id
     * @return      品牌详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<BrandDTO> queryBrandById(@PathVariable("id") Long id){
        BrandDTO brandDTO = brandService.queryBrandById(id);
        return ResponseEntity.ok(brandDTO);
    }

    /**
     * 批量查询品牌
     * @param brandIds
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity<List<BrandDTO>> queryBrandByIds(@RequestParam("ids") List<Long> brandIds){
        return ResponseEntity.ok(brandService.queryBrandByIds(brandIds));
    }
}
